package com.tanhua.server.service;

import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 圈子互动业务层
 */
@Service
@Slf4j
public class CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;


    /**
     * 圈子互动-评论列表分页查询
     *
     * @param page
     * @param pageSize
     * @param movementId
     * @return
     */
    public PageResult<CommentVo> findPageComments(Long page, Long pageSize, String movementId) {
        //1根据动态id分页查询评论列表数据
        PageResult<Comment> pageResult = commentApi.findPageComments(page,pageSize,movementId);
        if(CollectionUtils.isEmpty(pageResult.getItems())){
            return new PageResult<>(page,pageSize,0l,null);
        }
        List<Comment> commentList = pageResult.getItems();
        //2获取所有评论者ids
        List<Long> userIdsList = commentList.stream().map(Comment::getUserId).collect(Collectors.toList());
        //3根据评论者ids获取评论者用户信息
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIdsList, null);
        //4.基于评论数据与评论者用户信息 构造Vo
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Comment comment : commentList) {
            //userInfoMap.get(comment.getUserId()):注意 mysql数据库数据不能为空
            commentVoList.add(CommentVo.init(userInfoMap.get(comment.getUserId()),comment));
        }
        return new PageResult<>(page,pageSize,pageResult.getCounts(),commentVoList);
    }

    /**
     * 发布评论
     * @return
     */
    public void addComment(String publishId, String content) {
        Long userId = UserHolder.getUserId();//当前用户id
        //构造评论对象调用服务发布评论
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishId));//动态id:针对哪个动态进行评论
        comment.setCommentType(CommentType.COMMENT.getType());//评论类型：1-点赞，2-评论，3-喜欢
        comment.setContent(content);//评论内容
        comment.setUserId(userId);//评论人用户id
        commentApi.addComment(comment);
    }
}
